﻿using Services.Activity.WebApi.Response;
using Services.Initial.PublicProject.PublicClass.ExtensionException;
using Services.Initial.PublicProject.PublicClass.OutPutModels;
using System.Security.Claims;
using System.Text.Json;
using Zack.JWT;

namespace Service.Activity.SDK;

public class ActivityClient(ITokenService tokenService, JWTOptions jWTOptions, IHttpClientFactory httpClientFactory)
{
    private readonly IHttpClientFactory httpClientFactory = httpClientFactory;
    private readonly JWTOptions jWTOptions = jWTOptions;
    private readonly ITokenService tokenService = tokenService;
    private string BuildToken() 
    {
        //因为JWT的key等机密信息只有服务器端知道，因此可以这样非常简单的读到配置
        Claim claim = new Claim(ClaimTypes.Role, "Admin");
        return tokenService.BuildToken(new Claim[] { claim }, jWTOptions);
    }
    public  async Task<List<GetActivityVolunteerResponse>> GetActivityVolunteerAsync(long activityId)
    {
        string token = BuildToken();
        var httpClient = httpClientFactory.CreateClient();
        var uri = new Uri($"https://localhost:7122/Activity/GetActivityVolunteer?ActivityId={activityId}");
        httpClient.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", token);
        httpClient.Timeout = TimeSpan.FromSeconds(50);
        var httpResult = await httpClient.GetAsync(uri);
        if (httpResult.IsSuccessStatusCode)
        {
            var result = await httpResult.Content.ReadAsStringAsync();
            JsonSerializerOptions options = new() { PropertyNameCaseInsensitive = true };
            var jsonParse = JsonSerializer.Deserialize<OutputModel<List<GetActivityVolunteerResponse>>>(result, options);
            return jsonParse.Data;
        }
        else
        {
            throw new ExceptionWithStatus(System.Net.HttpStatusCode.BadRequest, "请求用户详情错误");
        }
    }
}
